<?php

namespace addons\crontab\controller;

use app\common\library\Auth;
use think\Controller;
use think\Db;
use think\Exception;

class Checkuser extends Controller
{
    /**
     * 初始化方法,最前且始终执行
     */
    public function _initialize()
    {
        // 只可以以cli方式执行
        if (!$this->request->isCli()) {
            $this->error('Checkuser script only work at client!');
        }

        parent::_initialize();

        // 清除错误
        error_reporting(0);

        // 设置永不超时
        set_time_limit(0);
    }

    /**
     * 执行定时任务
     */
    public function index()
    {
        echo "Checkuser START\n";
        $model = new \app\admin\model\User;
        Db::startTrans();
        try {
            $datetime = date('Y-m-d G:i:s');

            // 查询所有用户
            $users = $model->select();

            foreach ($users as &$user) {
                $start_time = $user['start_time'];
                $end_time = $user['end_time'];

                // 判断今天是否不在 $params['start_time'] 和 $params['end_time'] 之间
                if ($datetime < $start_time || $datetime > $end_time) {
                    // 踢号操作
                    Auth::instance()->kick($user['id']);
                    echo "Kick User, id=" . $user['id'] . "\n";
                }
            }

            echo "Checkuser COMPLETE\n";
            Db::commit();
        } catch (Exception $e) {
            echo $e->getMessage() . "\n";
            echo "Checkuser ERROR\n";
            Db::rollback();
        }
    }
}